// Obsidian进度追踪脚本
// 用于计算真实的任务完成进度

class ProgressTracker {
    constructor(app) {
        this.app = app;
    }

    // 计算文件夹中的任务完成率
    async calculateTaskProgress(folderPath) {
        const files = this.app.vault.getMarkdownFiles()
            .filter(file => file.path.startsWith(folderPath));
        
        let totalTasks = 0;
        let completedTasks = 0;
        
        for (const file of files) {
            const content = await this.app.vault.read(file);
            const tasks = this.extractTasks(content);
            
            totalTasks += tasks.total;
            completedTasks += tasks.completed;
        }
        
        return {
            total: totalTasks,
            completed: completedTasks,
            percentage: totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0
        };
    }

    // 提取任务信息
    extractTasks(content) {
        const taskRegex = /^[\s]*[-*+]\s*\[(.)\]/gm;
        const matches = [...content.matchAll(taskRegex)];
        
        const total = matches.length;
        const completed = matches.filter(match => match[1] === 'x' || match[1] === 'X').length;
        
        return { total, completed };
    }

    // 计算学习进度
    async calculateLearningProgress() {
        const learningFiles = this.app.vault.getMarkdownFiles()
            .filter(file => file.path.includes('学习') || 
                           file.tags?.includes('学习') ||
                           file.path.includes('003_wiki'));
        
        const thisMonth = new Date();
        thisMonth.setDate(1);
        
        const recentLearning = learningFiles.filter(file => 
            file.stat.mtime > thisMonth.getTime()
        );
        
        return {
            totalFiles: learningFiles.length,
            recentFiles: recentLearning.length,
            percentage: Math.round((recentLearning.length / Math.max(learningFiles.length, 1)) * 100)
        };
    }

    // 计算项目进度
    async calculateProjectProgress() {
        const projectFiles = this.app.vault.getMarkdownFiles()
            .filter(file => file.path.includes('002_prd') || 
                           file.path.includes('001_figma') ||
                           file.tags?.includes('需求'));
        
        let totalProjects = 0;
        let completedProjects = 0;
        
        for (const file of projectFiles) {
            const content = await this.app.vault.read(file);
            const frontmatter = this.app.metadataCache.getFileCache(file)?.frontmatter;
            
            if (frontmatter?.status) {
                totalProjects++;
                if (frontmatter.status === '已完成' || frontmatter.status === 'done') {
                    completedProjects++;
                }
            }
        }
        
        return {
            total: totalProjects,
            completed: completedProjects,
            percentage: totalProjects > 0 ? Math.round((completedProjects / totalProjects) * 100) : 0
        };
    }

    // 生成进度条HTML
    generateProgressBar(percentage, label, color = '#4CAF50') {
        return `
        <div class="progress-container">
            <div class="progress-label">${label}: ${percentage}%</div>
            <div class="progress-bar">
                <div class="progress-fill" style="width: ${percentage}%; background-color: ${color};">
                </div>
            </div>
        </div>
        `;
    }

    // 获取本周任务统计
    async getWeeklyTaskStats() {
        const weekStart = new Date();
        weekStart.setDate(weekStart.getDate() - weekStart.getDay());
        weekStart.setHours(0, 0, 0, 0);
        
        const weeklyFiles = this.app.vault.getMarkdownFiles()
            .filter(file => file.path.includes('周计划') && 
                           file.stat.mtime >= weekStart.getTime());
        
        let weeklyStats = {
            totalTasks: 0,
            completedTasks: 0,
            highPriority: 0,
            mediumPriority: 0,
            lowPriority: 0
        };
        
        for (const file of weeklyFiles) {
            const content = await this.app.vault.read(file);
            const tasks = this.extractTasksWithPriority(content);
            
            weeklyStats.totalTasks += tasks.total;
            weeklyStats.completedTasks += tasks.completed;
            weeklyStats.highPriority += tasks.p0;
            weeklyStats.mediumPriority += tasks.p1;
            weeklyStats.lowPriority += tasks.p2;
        }
        
        return weeklyStats;
    }

    // 提取带优先级的任务
    extractTasksWithPriority(content) {
        const lines = content.split('\n');
        let stats = { total: 0, completed: 0, p0: 0, p1: 0, p2: 0 };
        
        for (const line of lines) {
            if (line.match(/^[\s]*[-*+]\s*\[(.)\]/)) {
                stats.total++;
                
                if (line.includes('[x]') || line.includes('[X]')) {
                    stats.completed++;
                }
                
                if (line.includes('P0') || line.includes('紧急')) {
                    stats.p0++;
                } else if (line.includes('P1') || line.includes('重要')) {
                    stats.p1++;
                } else if (line.includes('P2')) {
                    stats.p2++;
                }
            }
        }
        
        return stats;
    }
}

// 导出给Obsidian使用
if (typeof module !== 'undefined') {
    module.exports = ProgressTracker;
}